#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的条码生成演示
专注于算法演示和ASCII输出
"""

from barcode_generator import generate_barcode, generate_barcode_number, find_valid_15bit_number, verify_15bit_condition

def create_simple_ascii_barcode(barcode_str, width=2):
    """
    创建简单的ASCII条码
    
    Args:
        barcode_str (str): 二进制条码字符串
        width (int): 每个条的宽度
    
    Returns:
        str: ASCII条码
    """
    if not barcode_str:
        return ""
    
    # 创建条码行
    bar_line = ""
    for bit in barcode_str:
        if bit == '1':
            bar_line += "█" * width  # 黑色块
        else:
            bar_line += " " * width  # 空白
    
    return bar_line

def analyze_algorithm_step_by_step(project_id, batch_id):
    """
    逐步分析算法过程
    
    Args:
        project_id (int): 项目编号
        batch_id (int): 批次
    """
    print(f"=== 算法逐步分析: 项目{project_id}, 批次{batch_id} ===")
    
    # 步骤1：计算条码编号
    barcode_number = generate_barcode_number(project_id, batch_id)
    print(f"步骤1 - 计算条码编号:")
    print(f"  公式: 项目编号 + (批次-1) * 80")
    print(f"  计算: {project_id} + ({batch_id}-1) * 80 = {project_id} + {(batch_id-1)*80} = {barcode_number}")
    
    # 步骤2：查找对应的15位数
    print(f"\n步骤2 - 查找第{barcode_number}个满足条件的15位数:")
    print(f"  条件: 15位二进制数按3位一组分组，每组中1的个数之和等于6")
    
    valid_number = find_valid_15bit_number(barcode_number)
    if valid_number is None:
        print("  错误：未找到有效数字")
        return
    
    print(f"  找到的数字: {valid_number} (十六进制: 0x{valid_number:04X})")
    
    # 验证条件
    is_valid, counts = verify_15bit_condition(valid_number)
    print(f"  验证: 组1={counts[0]}, 组2={counts[1]}, 组3={counts[2]}, 总和={counts[3]} {'✓' if is_valid else '✗'}")
    
    # 步骤3：转换为15位二进制
    binary_str = format(valid_number, '015b')
    print(f"\n步骤3 - 转换为15位二进制:")
    print(f"  二进制: {binary_str}")
    
    # 显示分组
    print(f"  分组显示:")
    for i in range(5):
        group = binary_str[i*3:(i+1)*3]
        ones = group.count('1')
        print(f"    组{i+1}: {group} (1的个数: {ones})")
    
    # 步骤4：编码转换
    print(f"\n步骤4 - 编码转换:")
    print(f"  规则: 偶数位1→A, 奇数位1→B, 偶数位0→C, 奇数位0→D")
    
    encoded = ""
    for i, bit in enumerate(binary_str):
        if bit == '1':
            if i % 2 == 0:
                encoded += 'A'
                print(f"    位{i}: '{bit}' (偶数位1) → A")
            else:
                encoded += 'B'
                print(f"    位{i}: '{bit}' (奇数位1) → B")
        else:
            if i % 2 == 0:
                encoded += 'C'
                print(f"    位{i}: '{bit}' (偶数位0) → C")
            else:
                encoded += 'D'
                print(f"    位{i}: '{bit}' (奇数位0) → D")
    
    print(f"  编码结果: {encoded}")
    
    # 步骤5：最终展开
    print(f"\n步骤5 - 最终展开:")
    print(f"  规则: A→'11', B→'00', C→'1', D→'0'")
    
    final_barcode = ""
    for char in encoded:
        if char == 'A':
            final_barcode += "11"
            print(f"    {char} → '11'")
        elif char == 'B':
            final_barcode += "00"
            print(f"    {char} → '00'")
        elif char == 'C':
            final_barcode += "1"
            print(f"    {char} → '1'")
        elif char == 'D':
            final_barcode += "0"
            print(f"    {char} → '0'")
    
    print(f"  最终条码: {final_barcode}")
    
    # 显示ASCII条码
    print(f"\n步骤6 - ASCII可视化:")
    ascii_barcode = create_simple_ascii_barcode(final_barcode)
    print(f"  条码长度: {len(final_barcode)}")
    print(f"  ASCII条码: {ascii_barcode}")
    
    # 显示详细的位置信息
    print(f"\n详细信息:")
    print(f"  位置: ", end="")
    for i in range(len(final_barcode)):
        print(f"{i%10}", end="")
    print()
    print(f"  数值: {final_barcode}")
    print(f"  条码: {ascii_barcode}")
    
    return final_barcode

def compare_multiple_barcodes():
    """比较多个条码的生成过程"""
    print("=== 多个条码比较 ===\n")
    
    test_cases = [
        (1, 1),   # 第1个
        (2, 1),   # 第2个
        (1, 2),   # 第81个
        (5, 3),   # 随机一个
    ]
    
    results = []
    for project_id, batch_id in test_cases:
        barcode_number = generate_barcode_number(project_id, batch_id)
        barcode = generate_barcode(project_id, batch_id)
        if barcode:
            results.append((project_id, batch_id, barcode_number, barcode))
    
    # 显示对比表格
    print("项目 | 批次 | 条码编号 | 条码长度 | 条码内容")
    print("-" * 60)
    for project_id, batch_id, barcode_number, barcode in results:
        print(f"{project_id:4d} | {batch_id:4d} | {barcode_number:8d} | {len(barcode):8d} | {barcode}")
    
    print("\nASCII可视化:")
    for project_id, batch_id, barcode_number, barcode in results:
        ascii_barcode = create_simple_ascii_barcode(barcode)
        print(f"P{project_id:02d}B{batch_id:02d}: {ascii_barcode}")

def interactive_demo():
    """交互式演示"""
    print("=== 交互式条码生成演示 ===")
    print("输入 'help' 查看帮助，输入 'quit' 退出\n")
    
    while True:
        try:
            user_input = input("请输入命令: ").strip().lower()
            
            if user_input == 'quit' or user_input == 'q':
                break
            elif user_input == 'help' or user_input == 'h':
                print("可用命令:")
                print("  generate <项目编号> <批次>  - 生成条码")
                print("  analyze <项目编号> <批次>   - 逐步分析算法")
                print("  compare                    - 比较多个条码")
                print("  help                       - 显示帮助")
                print("  quit                       - 退出")
            elif user_input == 'compare':
                compare_multiple_barcodes()
            elif user_input.startswith('generate '):
                parts = user_input.split()
                if len(parts) == 3:
                    project_id = int(parts[1])
                    batch_id = int(parts[2])
                    barcode = generate_barcode(project_id, batch_id)
                    if barcode:
                        ascii_barcode = create_simple_ascii_barcode(barcode)
                        print(f"条码: {barcode}")
                        print(f"ASCII: {ascii_barcode}")
                else:
                    print("用法: generate <项目编号> <批次>")
            elif user_input.startswith('analyze '):
                parts = user_input.split()
                if len(parts) == 3:
                    project_id = int(parts[1])
                    batch_id = int(parts[2])
                    analyze_algorithm_step_by_step(project_id, batch_id)
                else:
                    print("用法: analyze <项目编号> <批次>")
            else:
                print("未知命令，输入 'help' 查看帮助")
            
            print()
            
        except ValueError:
            print("错误：请输入有效的数字")
        except KeyboardInterrupt:
            break
    
    print("再见！")

def main():
    """主函数"""
    import sys
    
    if len(sys.argv) > 1:
        if sys.argv[1] == 'analyze' and len(sys.argv) == 4:
            project_id = int(sys.argv[2])
            batch_id = int(sys.argv[3])
            analyze_algorithm_step_by_step(project_id, batch_id)
        elif sys.argv[1] == 'compare':
            compare_multiple_barcodes()
        else:
            print("用法:")
            print("  python simple_barcode_demo.py                    # 交互模式")
            print("  python simple_barcode_demo.py analyze <项目> <批次>  # 逐步分析")
            print("  python simple_barcode_demo.py compare            # 比较多个条码")
    else:
        # 默认运行演示
        print("条码生成算法演示\n")
        analyze_algorithm_step_by_step(1, 1)
        print("\n" + "="*60 + "\n")
        compare_multiple_barcodes()
        print("\n" + "="*60 + "\n")
        interactive_demo()

if __name__ == "__main__":
    main()
